var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var CommentSchema = new Schema({
    movie: { // 当前要评论的电影是哪个电影
        type: ObjectId, 
        ref: 'Movie'
    },
    from: {
        type: ObjectId, 
        ref: 'User'
    },
    reply: [{
        from: { type: ObjectId, ref: 'User' },
        to: { type: ObjectId, ref: 'User' },
        content: String
    }],
    content: String, 
    meta: {
        createAt: {
            type: Date,
            default: Date.now()
        },
        updateAt: {
            type: Date,
            default: Date.now()
        }
    },
})

CommentSchema.pre('save', function() {
    if (this.isNew) {
        this.meta.createAt = this.meta.updateAt = Date.now()
    } else {
        this.meta.updateAt = Date.now()
    }

    next()
})

CommentSchema.statics = {
    fetch: function(cb) { // 取出数据库所有数据
        return this
            .find({})
            .sort('meta.updateAt')
            .exec(cb)
    },
    findById: function(id, cb) { // 取出数据单条所有数据
        return this
            .findOne({ _id: id })
            .exec(cb)
    }
}

module.exports = CommentSchema